package com.example.wxsmart.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import java.io.IOException;
import java.util.Objects;

/**
 * @author Luojunxian
 * @data 2022/5/30 14:20
 * @classname OkHttpUtil
 */
public class OkHttpUtil {

    public static String sendGet(String url) {
        OkHttpClient client = new OkHttpClient();
        String result = null;
        Call call = client.newCall(new Request.Builder().get().url(url).build());

        try {
            Response execute = call.execute();
            result = Objects.requireNonNull(execute.body()).string();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    public static String sendPost(String url, JSONObject jsonObject) {
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = RequestBody.create(jsonObject.toString(), MediaType.parse("application/json;charset=utf-8"));
        String result = null;
        Call call = client.newCall(new Request.Builder().url(url).post(requestBody).build());

        try {
            Response execute = call.execute();
            result = Objects.requireNonNull(execute.body()).string();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    public static void main(String[] args) throws IOException {

        String url1 = String.format("%s?corpid=%s&corpsecret=%s", "https://qyapi.weixin.qq.com/cgi-bin/gettoken",
                "ww99654075f8e9b3f2", "Xn4X13xxzbisbvnQ1_5MGYkh1fanGHEGe11Xl5Luutc");

        JSONObject result = JSON.parseObject(sendGet(url1));
        String access_token = result.getString("access_token");
        System.out.println(access_token);
        String url = String.format("%s?access_token=%s", "https://qyapi.weixin.qq.com/cgi-bin/message/send", access_token);

        JSONObject json = new JSONObject();
        json.put("touser", "LuoJunXian");
        json.put("msgtype", "text");
        json.put("agentid", 1000002);
        JSONObject jsonObject = new JSONObject();
        //Content = JieBa.jieBaFenCi(Content);
        jsonObject.put("content", "你的快递已到，请携带工卡前往邮件中心领取。\\n出发前可查看<a href=\\\"http://work.weixin.qq.com\\\">邮件中心视频实况</a>，聪明避开排队");
        json.put("text", jsonObject);
        json.put("safe", 0);

        String s = sendPost(url, json);
        System.out.println(s);
    }
}
